package com.ljc.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.code.kaptcha.Producer;
import com.ljc.common.lang.Result;
import com.ljc.entity.User;
import com.ljc.utils.ValidationUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.Security;

/**
 * @Author: ljc
 * @Date:Created in 8:57 2021/12/21
 */
@Controller
public class AuthController extends BaseController {
    public static final String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    @Autowired
    Producer producer;

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @GetMapping("/register")
    public String reg() {
        return "/auth/reg";
    }

    /**
     * 神生成验证阿
     *
     * @Author: ljc
     * @Date:Created in 10:55 2021/12/21
     */
    @GetMapping("/capthca.jpg")
    public void kaptcha(HttpServletResponse resp) throws IOException {
        //验证码
        String text = producer.createText();
        //验证码存到session中用于校验
        httpServletRequest.getSession().setAttribute("KAPTCHA_SESSION_KEY", text);

        BufferedImage image = producer.createImage(text);
        //设置页面缓存不刷新
        resp.setHeader("Cache-Control", "no-store,no-cache");
        //设置响应头格式
        resp.setContentType("image/jepg");
        ServletOutputStream outputStream = resp.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
    }

    @ResponseBody
    @PostMapping("/login")
    public Result doLogin(String email, String password) {
        if (StrUtil.isEmpty(email) || StrUtil.isBlank(password)) {
            return Result.fail("邮箱或密码不能为空");
        }
        UsernamePasswordToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));

        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在");
            }
            else if (e instanceof LockedAccountException){
                return Result.fail("用户被禁用");
            }
            else if (e instanceof IncorrectCredentialsException){
                return Result.fail("密码错误");
            }
            else{
                return  Result.fail("用户认证失败");
            }
        }
        return Result.success().action("/");
    }

    /**
     * 注册响应
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/register")
    public Result doRegister(User user, String repass, String vercode) {
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(user);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }

        if (!repass.equals(user.getPassword())) {
            return Result.fail("两次密码不一致!");
        }

        String kaptcha_session_key = (String) httpServletRequest.getSession().getAttribute("KAPTCHA_SESSION_KEY");
        System.out.println(kaptcha_session_key);
        if (vercode == null || !vercode.equalsIgnoreCase(kaptcha_session_key)) {
            return Result.fail("验证码错误!");
        }
        //完成注册
        Result res = userService.register(user);
        return res.action("/login");
    }

    @RequestMapping("/user/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }

}
